package com.fortune.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.fortune.common.paging.PagingData;
import com.fortune.util.CacheManager;
import com.fortune.vo.cache.Cache;
import com.fortune.vo.cache.TimeOut;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.fortune.base.BaseAPIExcution;
import com.fortune.common.redis.RedisClient;
import com.fortune.constants.Constants;
import com.fortune.constants.redis.CacheKeys;
import com.fortune.dto.excution.DUserExcution;
import com.fortune.dto.in.dUser.DChangePasswordDto;
import com.fortune.dto.in.dUser.DLoginDto;
import com.fortune.dto.in.dUser.DResetPasswordDto;
import com.fortune.entity.DUserInfo;
import com.fortune.enums.DUserEnum;
import com.fortune.service.DPermissionService;
import com.fortune.service.DUserService;
import com.fortune.vo.dUser.LoginDUserInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Api(value = "duser", description = "经销商员工账号相关", tags = {"经销商员工账号相关"})
@RestController
@RequestMapping("dUser")
public class DUserController{
	
	@Autowired
	private DUserService dUserService;
	@Autowired
	private RedisClient redisClient;
	@Autowired
	private DPermissionService dPermissionService;

	@ApiOperation(value = "经销商员工登录", nickname = "dUserLogin", notes = "", tags={ "@岳希伟" })
    @PostMapping(value = "login",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<LoginDUserInfo> login(HttpServletRequest request,@Validated @RequestBody DLoginDto dloginDto) {
			int check = dUserService.loginCheck(dloginDto);
			if (check==1) {
				return new DUserExcution<LoginDUserInfo>(null, DUserEnum.PASSWORDFALSE);
			}else if (check==2) {
				return new DUserExcution<LoginDUserInfo>(null, DUserEnum.PHONEFALSE);
			}else {
				DUserInfo dUserInfo = dUserService.dUserInfo(dloginDto);
				if(dUserInfo == null){
					return new DUserExcution<LoginDUserInfo>(null, DUserEnum.UFAIL);
				}
				int counts = dUserService.findAccountStatusd(dUserInfo.getdId());
				if(counts != 0){
					return new DUserExcution<LoginDUserInfo>(null, DUserEnum.DELETESTATUSD);
				}
				int count = dUserService.findAccountStatus(dUserInfo.getdId());
				if(count == 0){
					return new DUserExcution<LoginDUserInfo>(null, DUserEnum.DELETESTATUS);
				}
				//缓存。。。。。。。。。。。。。。。。。。
				Random ra =new Random();
				int as = ra.nextInt(1000)+1;
				dUserInfo.setRandom(as);
				int num = dUserService.findMaxConnect(dUserInfo.getdId());  //查该经销商的最大登录人上限
				HashMap map = new HashMap();
				//new 一个list，new 一个实体，set值
				List<TimeOut> list11 = new ArrayList<>();
				List<TimeOut> noTimeOut = new ArrayList<>();
				TimeOut timeOut = new TimeOut();
				timeOut.setdId(dUserInfo.getdId());
				timeOut.setId(dUserInfo.getId());
				timeOut.setRandom(as);
				///获取key为cache + 经销商ID 的缓存
				String key = CacheManager.cache;
				key = key+"Did:"+dUserInfo.getdId();
				Cache cache= CacheManager.getCacheInfo(key);
				//如果cache 里没数据 吧这次登陆的人加进去
				if(cache == null){
					list11.add(timeOut);
					cache = new Cache();
					cache.setKey(key);
					cache.setValue(list11);
					CacheManager.putCache(key, cache);
				}else{
					for(int i =0; i< cache.getValue().size(); i++){
						TimeOut timeOut1 = cache.getValue().get(i);
						if(timeOut1.getId().equals(dUserInfo.getId())){
							cache.getValue().remove(timeOut1);
						}
						long a = timeOut1.getTimeOut()+1000*60*30;
						long t1=System.currentTimeMillis();
						if(a <= t1){
							noTimeOut.add(timeOut1);
						}
					}
					//如果该经销商下的人数上限高于或等于该经销商下的人数上限的话就不让他登陆了
					if(cache.getValue().size() >= num){
						return new DUserExcution<LoginDUserInfo>(null, DUserEnum.LOGINFAIL);
					}else{
						cache.getValue().add(timeOut);
						CacheManager.putCache(key, cache);
					}
				}

				//缓存。。。。。。。。。。。。。。。。。。
				HttpSession session = request.getSession();
				session.setAttribute(Constants.SESSION_D_USER, dUserInfo);
				String dId = dUserInfo.getdId();
				String positonId = dUserInfo.getDpostionId();
				List<String> permissions = dPermissionService.listPermissions(dId, positonId);
				session.setAttribute(Constants.SESSION_PERMISSION, permissions);
				LoginDUserInfo loginDUserInfo = dUserService.loginDUserInfo(dloginDto);
				return new DUserExcution<LoginDUserInfo>(loginDUserInfo, DUserEnum.SUCCESS);
			}
	}
	
	@ApiOperation(value = "经销商员工退出登录", nickname = "dUserLogout", notes = "", tags={ "@岳希伟" })
    @PostMapping(value = "logout")
	public BaseAPIExcution<Void> logount(HttpServletRequest request) {
		HttpSession session = request.getSession();
		DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
		dUserInfo.getId();
		String key = "cache"+"Did:"+dUserInfo.getdId();
		Cache cache= CacheManager.getCacheInfo(key);
		for(TimeOut timeOut:cache.getValue()){
			if(timeOut.getId().equals(dUserInfo.getId())){
				CacheManager.clearOnly(key);
			}
		}
		session.invalidate();
		return new DUserExcution<Void>(null,DUserEnum.SUCCESS);
	}
	
	@ApiOperation(value = "经销商员工重置密码", nickname = "dUserResetPassword", notes = "", tags={ "@岳希伟" })
    @PostMapping(value = "password/reset",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> resetPassword(HttpServletRequest request,@Validated @RequestBody DResetPasswordDto dResetPasswordDto) {
		String check = redisClient.get(CacheKeys.EMAIL_SEND_CODE, dResetPasswordDto.getPhone());
		if (check==null || check.isEmpty()) {
			return new DUserExcution<Void>(null, DUserEnum.SESSIONCODEFALSE);
		}
		if (check.equals(dResetPasswordDto.getCode())) {
		/*	HttpSession session = request.getSession();
			DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
			if (dUserInfo==null) {
				return new DUserExcution<Void>(null, DUserEnum.NOLOGIN);
			}*/
			int result = dUserService.resetPassword(dResetPasswordDto);
			if (result==1) {
				return new DUserExcution<Void>(null, DUserEnum.SUCCESS);
			}
			return new DUserExcution<Void>(null, DUserEnum.EEE);
		}
		return new DUserExcution<Void>(null, DUserEnum.CODEFALSE);
	}
	
	@ApiOperation(value = "经销商员工修改密码", nickname = "dUserChangePassword", notes = "", tags={ "@岳希伟" })
    @PostMapping(value = "password/change",
    	produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> changePassword(HttpServletRequest request,@Validated @RequestBody DChangePasswordDto dChangePasswordDto) {
		HttpSession session = request.getSession();
		DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
		if (dUserInfo==null) {
			return new DUserExcution<Void>(null, DUserEnum.NOLOGIN);
		}
		int result =dUserService.updatePassword(dUserInfo, dChangePasswordDto);
		if (result > 0) {
			return new DUserExcution<Void>(null, DUserEnum.SUCCESS);
		}else{
			return new DUserExcution<Void>(null, DUserEnum.PASSWORDFALSE);
		}

	}


	@ApiOperation(value = "经销商", nickname = "dUserList", notes = "@安童")
	@GetMapping(value = "fid",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<DUserInfo> list(HttpServletRequest request) {
		HttpSession session = request.getSession();
		DUserInfo dUserInfo = (DUserInfo) session.getAttribute(Constants.SESSION_D_USER);
		DUserInfo aa = dUserService.fid(dUserInfo.getdId());
		dUserInfo.setDidName(aa.getDidName());
		return new DUserExcution<DUserInfo>(dUserInfo, DUserEnum.SUCCESS);
	}



}
